﻿using System;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Windows.Forms;

namespace Container
{
    public class TcpServer
    {
        private static Socket connection;

        // 创建一个和客户端通信的套接字
        static Socket socketwatch = null;

        private string info ="打印消息:"+"\n";

        public static void ServerStart()
        {
            //定义一个套接字用于监听客户端发来的消息，包含三个参数（IP4寻址协议，流式连接，Tcp协议）  
            socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //服务端发送信息需要一个IP地址和端口号  
            IPAddress address = IPAddress.Parse("127.0.0.1");
            //将IP地址和端口号绑定到网络节点point上  
            IPEndPoint point = new IPEndPoint(address, 8098);

            //监听绑定的网络节点  
            socketwatch.Bind(point);

            //将套接字的监听队列长度限制为20  
            socketwatch.Listen(20);

            //负责监听客户端的线程:创建一个监听线程  
            Thread threadwatch = new Thread(ServerWatch);

            //将窗体线程设置为与后台同步，随着主线程结束而结束  
            threadwatch.IsBackground = true;

            //启动线程     
            threadwatch.Start();

            TipLog("创建服务器成功！");
        }

        //监听客户端发来的请求  
        private static void ServerWatch()
        {
            //持续不断监听客户端发来的请求     
            while (true)
            {
                try
                {
                    connection = socketwatch.Accept();
                }
                catch (Exception ex)
                {
                    //提示套接字监听异常     
                    Console.WriteLine(ex.Message);
                    break;
                }

                //客户端网络结点号  
                string remoteEndPoint = connection.RemoteEndPoint.ToString();

                //显示与客户端连接情况
                TipLog("新连接："+remoteEndPoint);


                //创建一个通信线程      
                ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerReceive);
                Thread thread = new Thread(pts);

                //设置为后台线程，随着主线程退出而退出 
                thread.IsBackground = true;
                //启动线程     
                thread.Start(connection);
            }
        }

        // 接收客户端发来的信息，客户端套接字对象
        private static void ServerReceive(object socketclientpara)
        {
            Socket socketServer =(Socket) socketclientpara;

            while (true)
            {
                //创建一个内存缓冲区，其大小为1024*1024字节  即1M     
                byte[] arrServerRecMsg = new byte[1024 * 1024];
                //将接收到的信息存入到内存缓冲区，并返回其字节数组的长度    
                try
                {
                    int length = socketServer.Receive(arrServerRecMsg);

                    //将机器接受到的字节数组转换为人可以读懂的字符串     
                    string message = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
                    TipLog("收到消息:" + message);
                }
                catch (Exception ex)
                {

                    //提示套接字监听异常 
                    TipLog("已经中断连接"); 
                    //关闭之前accept出来的和客户端进行通信的套接字 
                    socketServer.Close();
                    break;
                }
            }
        }

        public static void ServerSend(string message)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(message);
            connection.Send(bytes);
            TipLog("发送数据:"+message);
        }

        public static void ServerClosed()
        {
            socketwatch.Close();
            connection.Close();
        }

        // 获取当前系统时间的方法    
        private  static DateTime GetCurrentTime()
        {
            DateTime currentTime = new DateTime();
            currentTime = DateTime.Now;
            return currentTime;
        }

        private static void TipLog(string info)
        {
            Form1.Instant.info.Text += info + "\r\n";
        }
    }
}
